package com.green.card.smscode;

import android.content.Context;

import com.google.gson.Gson;
import com.green.card.bean.GenruiSmsResultBean;
import com.green.card.constants.Config;
import com.green.card.utils.ZYALogUtils;
import com.zhuoyian.analysis.util.EncodeUtil;
import com.zyasdk.util.SP;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by admin on 2018/1/30.
 * @des 创瑞云短信接口
 */

public class GenruiSmsCode {
    /**
     * 使用SP保存到本地的唯一批处理的ID
     */
    private static final String BATCHID = Config.BATCHID;

    private static int    mSmsCode;//短信验证码
    private static String mBatchId;// 系统生成的唯一批处理ID

    public static int getmSmsCode() {
        return mSmsCode;
    }

    /**
     * 发送请求获取短信验证码
     * @param phoneNumber
     *          手机号码
     */
    public static void sendVerificationCode(final Context context, String phoneNumber) {
        try {
            //短信验证码
            mSmsCode = getSmsCode();
            OkHttpClient client = new OkHttpClient();
            String accesskey = "boNtBrGwrVWjNpK8";//平台分配给用户的AccessKey，登录系统首页可点击"我的秘钥"查看
            String secret = "47vRXhmgTBbeTqL5YsgyGQ5xDs4Ju2JO";//平台分配给用户的AccessSecret，登录系统首页可点击"我的秘钥"查看
            String sign = "2133";//平台上申请的接口短信签名或者签名ID（须审核通过）
            String templateId = "3598";//平台上申请的接口短信模板Id
            String mobile = phoneNumber;//接收短信的手机号码，多个号码以半角逗号,隔开
            String content = EncodeUtil.decoderUTF8(mSmsCode+"##60");//短信的内容，内容需要UTF-8编码
            ZYALogUtils.d("mSmsCode-->"+mSmsCode);
            //Form表单格式的参数传递
            FormBody formBody = new FormBody
                    .Builder()
                    .add("accesskey", accesskey)
                    .add("secret", secret)
                    .add("sign",sign)
                    .add("templateId", templateId)
                    .add("mobile", mobile)
                    .add("content",content)
                    .build();
            Request request = new Request.Builder()
                    .url(Config.GENRUI_SMS_URL)
                    .post(formBody)
                    .build();
            Call call = client.newCall(request);
            // 这里是测试使用，代码可删除
         //   parseJsonObject(context,"{\"code\":\"0\",\"msg\":\"SUCCESS\",\"batchId\":\"1362140\"}");

            //异步请求短信验证码平台
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    ZYALogUtils.e("短信平台请求-->"+e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    ZYALogUtils.d("短信平台result-->"+result);
                    parseJsonObject(context,result);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析返回的json数据
     * @param result
     *      成功请求返回的数据
     */
    private static void parseJsonObject(Context context, String result) {
        Gson gson = new Gson();
        GenruiSmsResultBean smsResultBean = gson.fromJson(result, GenruiSmsResultBean.class);
        String msg = smsResultBean.msg;
        ZYALogUtils.d("msg-->"+msg);
        //我们一般都将常量放前面,防止errorCode为null时抛空指针异常
        if ("SUCCESS".equals(msg)){// 请求成功
            // 批次id
            mBatchId = smsResultBean.batchId;
            // 保存到本地
            SP.put(context,BATCHID, mBatchId);
        }
    }

    /**
     * 返回自定义的验证码，6位数据
     * @return
     */
    private static int getSmsCode(){
        int smsCode = (int) ((Math.random()*9+1)*100000);
        return smsCode;
    }
}
